package com.imflea.zero.model.entity.wx.config;

import com.imflea.zero.utils.Base64Util;
import com.github.wxpay.sdk.IWXPayDomain;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class FarmWXPayConfig extends WXPayConfig {
    private String appId;
    private String mchId;
    private String key;
    private String certContent;
    private String notifyUrl;

    private byte[] certData;


    public FarmWXPayConfig(String certPath) throws Exception {
        //String certPath = "/path/to/apiclient_cert.p12";
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();

    }


    public FarmWXPayConfig(String appId, String mchId, String key, String certContent) {
        this.appId = appId;
        this.mchId = mchId;
        this.key = key;
        this.certContent = certContent;
    }
    public FarmWXPayConfig(String appId, String mchId, String key, String certContent,String notifyUrl) {
        this.appId = appId;
        this.mchId = mchId;
        this.key = key;
        this.certContent = certContent;
        this.notifyUrl = notifyUrl;
    }

    public FarmWXPayConfig() {
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getAppID() {
        return this.appId;
    }

    public String getMchID() {
        return this.mchId;
    }

    private void setMchID(String mchID) {
        this.mchId = this.mchId;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getKey() {
        return this.key;
    }


    public void setCertContent(String certContent) {
        this.certContent = certContent;
    }

    public InputStream getCertStream() {
        String tempCertContent = this.certContent.substring(this.certContent.indexOf("base64,") + 7);
        ByteArrayInputStream certBis = new ByteArrayInputStream(Base64Util.base64Decode(tempCertContent));
        return certBis;
    }

    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }

    public String getNotifyUrl() {
        return notifyUrl;
    }

    public void setNotifyUrl(String notifyUrl) {
        this.notifyUrl = notifyUrl;
    }

    @Override
    public IWXPayDomain getWXPayDomain() {
        IWXPayDomain iwxPayDomain = new IWXPayDomain() {

            public void report(String domain, long elapsedTimeMillis, Exception ex) {

            }

            public DomainInfo getDomain(WXPayConfig config) {
                return new DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
        return iwxPayDomain;
    }
}